using System;
using System.IO;

using octalforty.Componento.ComponentModel.Packaging;
using octalforty.Componento.SemanticModel;

namespace octalforty.Componento.ComponentModel.Commanding
{
    [Command("list")]
    public class ListCommand : ICommand
    {
        #region ICommand Members
        public void Execute(Core.IServiceProvider serviceProvider, CommandArgumentContainer arguments)
        {
            Uri repositoryUri = new Uri("http://repository.componento.net");

            if(arguments.Contains("--local") || !arguments.Contains("--remote"))
            {
                if(arguments.Contains("--source"))
                    repositoryUri = new Uri(arguments.ValueAfter("--source"), UriKind.Absolute);
                else
                    repositoryUri = new Uri(string.Format("file://{0}", Directory.GetCurrentDirectory()));
            } // if
            else if(arguments.Contains("--remote"))
            {
                if(arguments.Contains("--source"))
                    repositoryUri = new Uri(arguments.ValueAfter("--source"), UriKind.Absolute);
            } // else

            Console.WriteLine("Listing packages in {0}", repositoryUri);

            IPackageRepositoryBrowserProviderService repositoryBrowserProvider =
                serviceProvider.GetService<IPackageRepositoryBrowserProviderService>();
            IRepositoryBrowser repositoryBrowser =
                repositoryBrowserProvider.GetPackageRepositoryBrowser(repositoryUri);

            foreach(RepositoryEntry repositoryEntry in repositoryBrowser.OpenRepository(repositoryUri).Entries)
            {
                Console.WriteLine("{0} ({1})", repositoryEntry.Name, repositoryEntry.Version);
            } // foreach
        }
        #endregion
    }
}
